#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <taskLib.h>
#include "Api7841.h"
#include "Commdef.h"


static void DumpCanPacket(int iCardNo, int iPortNo, CAN_PACKET *pPacket)
{
	int i;
	printf("CAN Message Dumping, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
	printf("\tCAN ID: %08X\n", pPacket->canId);
	printf("\tRTR: %d\n", pPacket->rtr);
	printf("\tLength: %d\n", pPacket->len);
	printf("\tData: ");
	for (i = 0; i < 8; ++i)
	{
		printf("%02X", pPacket->data[i]);
	}
	printf("\n\n");
}

int CanReadTest(int iCardNo, int iPortNo, int iPeriod)
{
	CAN_PACKET recvPacket;
	int iRecvCnt, i;
	int iRetVal;
	int iHandle = CanOpenDriver(iCardNo, iPortNo); 
	if (iHandle == -1)
	{
		printf("\n CAN Open Failed, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
		return -1;
	}
	CanClearRxBuffer(iHandle);
	
	while (1)
	{
		iRecvCnt = CanGetRcvCnt(iHandle);
		
		for (i = 0; i < iRecvCnt; ++i)
		{
			iRetVal = CanRcvMsg(iHandle, &recvPacket);
			if (iRetVal != -1)
			{
				DumpCanPacket(iCardNo, iPortNo, &recvPacket);
			}
			else
			{
				printf("CAN Read Message Failed, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
				break;
			}
		}
		taskDelay(iPeriod);
	}
	CanCloseDriver(iHandle);
}

int CanWriteTest(int iCardNo, int iPortNo, int iPeriod)
{
	CAN_PACKET sndPacket;

	int iRetVal;
	int iIdCounter, iDataCounter;
	int i;
	iIdCounter = 0;
	iDataCounter = 0;
	
	int iHandle = CanOpenDriver(iCardNo, iPortNo); 
	if (iHandle == -1)
	{
		printf("\n CAN Open Failed, CardNo = %d, PortNo = %d\n", iCardNo, iPortNo);
		return -1;
	}
	CanClearTxBuffer(iHandle);

	sndPacket.rtr = 0;
	sndPacket.len = 8;
	
	while (1)
	{
		sndPacket.canId = 0x01;/*iIdCounter++;*/
		for (i = 0; i < 8; ++i)
		{
			sndPacket.data[i] = i+2;/*iDataCounter++*/;
		}
		
		iRetVal = CanSendMsg(iHandle, &sndPacket);
		if (iRetVal != -1)
		{
			printf("CAN Message send succeed\n");
			/*DumpCanPacket(iCardNo, iPortNo, &sndPacket);*/
		}
		taskDelay(iPeriod);
	}
	CanCloseDriver(iHandle);
}


void ReadTest()
{
	CanReadTest(0,0,2);
}

void Read1Test()
{
	CanReadTest(1,0,2);
}

void WriteTest()
{
	CanWriteTest(1,0,2);
}
